from flask import Blueprint, jsonify, request, current_app
import uuid
import datetime
from functools import wraps

from src.models.bazi_models import db, BaziRecord, BaziAnalysis
from src.routes.auth import token_required

bazi_bp = Blueprint('bazi', __name__)

# 八字分析
@bazi_bp.route('/analysis', methods=['POST'])
def bazi_analysis():
    data = request.json
    
    # 验证必要字段
    if not data or not data.get('year') or not data.get('month') or not data.get('day') or not data.get('gender'):
        return jsonify({
            'code': 400,
            'message': '请提供完整的出生年月日和性别信息',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 400
    
    # 获取用户ID（如果已登录）
    user_id = None
    token = None
    if 'Authorization' in request.headers:
        auth_header = request.headers['Authorization']
        try:
            token = auth_header.split(" ")[1]
            payload = jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=['HS256'])
            user_id = payload['sub']
        except:
            # 忽略token错误，视为游客访问
            pass
    
    # 生成八字ID
    bazi_id = f"bz{uuid.uuid4().hex[:10]}"
    
    # 计算农历日期（简化处理，实际应使用专业库进行公历转农历）
    # TODO: 使用专业库进行公历转农历
    lunar_year = data.get('year')
    lunar_month = data.get('month')
    lunar_day = data.get('day')
    lunar_hour = data.get('hour', 12)
    
    # 计算天干地支（简化处理，实际应使用专业算法）
    # TODO: 使用专业算法计算天干地支
    tian_gan = "甲乙丙丁戊己庚辛壬癸"[data.get('year') % 10]
    di_zhi = "子丑寅卯辰巳午未申酉戌亥"[data.get('year') % 12]
    wu_xing = "金木水火土"[data.get('year') % 5]
    na_yin = "海中金"  # 简化处理
    
    # 创建八字记录
    bazi_record = BaziRecord(
        bazi_id=bazi_id,
        user_id=user_id,
        name=data.get('name'),
        gender=data.get('gender'),
        birth_year=data.get('year'),
        birth_month=data.get('month'),
        birth_day=data.get('day'),
        birth_hour=data.get('hour', 12),
        lunar_year=lunar_year,
        lunar_month=lunar_month,
        lunar_day=lunar_day,
        lunar_hour=lunar_hour,
        tian_gan=tian_gan,
        di_zhi=di_zhi,
        wu_xing=wu_xing,
        na_yin=na_yin,
        create_time=datetime.datetime.now(),
        update_time=datetime.datetime.now()
    )
    
    # 创建八字分析
    basic_summary = f"{data.get('year')}年{data.get('month')}月{data.get('day')}日出生，八字为{tian_gan}{di_zhi}，五行属{wu_xing}，纳音为{na_yin}。"
    character_summary = "性格温和，做事认真，有责任心，善于思考。" # 简化处理
    
    # 付费内容（简化处理）
    destiny_analysis = "命运轨迹详解内容，需要付费查看。"
    career_analysis = "事业发展分析内容，需要付费查看。"
    wealth_analysis = "财运分析内容，需要付费查看。"
    relationship_analysis = "人际关系分析内容，需要付费查看。"
    health_analysis = "健康状况分析内容，需要付费查看。"
    general_suggestion = "一般建议内容，需要付费查看。"
    specific_suggestion = "针对性建议内容，需要付费查看。"
    
    bazi_analysis = BaziAnalysis(
        bazi_id=bazi_id,
        basic_summary=basic_summary,
        character_summary=character_summary,
        destiny_analysis=destiny_analysis,
        career_analysis=career_analysis,
        wealth_analysis=wealth_analysis,
        relationship_analysis=relationship_analysis,
        health_analysis=health_analysis,
        general_suggestion=general_suggestion,
        specific_suggestion=specific_suggestion,
        is_paid=0,
        create_time=datetime.datetime.now(),
        update_time=datetime.datetime.now()
    )
    
    try:
        db.session.add(bazi_record)
        db.session.add(bazi_analysis)
        db.session.commit()
        
        # 构建响应数据
        response_data = {
            'baziId': bazi_id,
            'basicInfo': {
                'tianGan': tian_gan,
                'diZhi': di_zhi,
                'wuXing': wu_xing,
                'naYin': na_yin
            },
            'freeAnalysis': {
                'summary': basic_summary,
                'character': character_summary
            },
            'needPayment': True,
            'paymentInfo': {
                'price': 1.1,
                'memberPrice': 0.1
            }
        }
        
        return jsonify({
            'code': 200,
            'message': '分析成功',
            'data': response_data,
            'timestamp': datetime.datetime.now().timestamp()
        }), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'分析失败: {str(e)}',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 500

# 获取八字详细分析（付费内容）
@bazi_bp.route('/analysis/<bazi_id>/detail', methods=['GET'])
def get_bazi_detail(bazi_id):
    # 查询八字分析
    bazi_analysis = BaziAnalysis.query.filter_by(bazi_id=bazi_id).first()
    if not bazi_analysis:
        return jsonify({
            'code': 404,
            'message': '未找到相关八字分析',
            'data': None,
            'timestamp': datetime.datetime.now().timestamp()
        }), 404
    
    # 检查是否已付费
    if bazi_analysis.is_paid == 0:
        # 获取用户ID（如果已登录）
        user_id = None
        is_vip = False
        token = None
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            try:
                token = auth_header.split(" ")[1]
                payload = jwt.decode(token, current_app.config.get('SECRET_KEY'), algorithms=['HS256'])
                user_id = payload['sub']
                
                # 检查是否是VIP会员
                from src.models.user_models import UserVip
                vip_info = UserVip.query.filter_by(user_id=user_id, status=1).first()
                if vip_info and vip_info.expire_time > datetime.datetime.now():
                    is_vip = True
            except:
                # 忽略token错误，视为游客访问
                pass
        
        # 如果不是VIP会员，需要付费
        if not is_vip:
            return jsonify({
                'code': 403,
                'message': '需要付费查看详细分析',
                'data': {
                    'needPayment': True,
                    'paymentInfo': {
                        'price': 1.1,
                        'memberPrice': 0.1
                    }
                },
                'timestamp': datetime.datetime.now().timestamp()
            }), 403
    
    # 构建响应数据
    response_data = {
        'baziId': bazi_id,
        'detailAnalysis': {
            'destiny': bazi_analysis.destiny_analysis,
            'career': bazi_analysis.career_analysis,
            'wealth': bazi_analysis.wealth_analysis,
            'relationship': bazi_analysis.relationship_analysis,
            'health': bazi_analysis.health_analysis
        },
        'solutions': {
            'general': bazi_analysis.general_suggestion,
            'specific': bazi_analysis.specific_suggestion
        }
    }
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': response_data,
        'timestamp': datetime.datetime.now().timestamp()
    }), 200

# 获取用户的八字记录列表
@bazi_bp.route('/records', methods=['GET'])
@token_required
def get_user_bazi_records(current_user):
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    records = BaziRecord.query.filter_by(user_id=current_user.id).order_by(BaziRecord.create_time.desc()).paginate(page=page, per_page=per_page)
    
    records_list = []
    for record in records.items:
        analysis = BaziAnalysis.query.filter_by(bazi_id=record.bazi_id).first()
        basic_summary = analysis.basic_summary if analysis else ""
        
        records_list.append({
            'baziId': record.bazi_id,
            'name': record.name,
            'gender': record.gender,
            'birthYear': record.birth_year,
            'birthMonth': record.birth_month,
            'birthDay': record.birth_day,
            'birthHour': record.birth_hour,
            'tianGan': record.tian_gan,
            'diZhi': record.di_zhi,
            'wuXing': record.wu_xing,
            'naYin': record.na_yin,
            'summary': basic_summary,
            'createTime': record.create_time.strftime('%Y-%m-%d %H:%M:%S')
        })
    
    return jsonify({
        'code': 200,
        'message': '获取成功',
        'data': {
            'records': records_list,
            'pagination': {
                'total': records.total,
                'pages': records.pages,
                'page': records.page,
                'per_page': records.per_page
            }
        },
        'timestamp': datetime.datetime.now().timestamp()
    }), 200
